/**
 * Created by visten on 15-1-17.
 * 可以直接使用
 */
var Browser = {
    runIfInTopFrame: function (a) {
        navigator.userAgent.match(/chrome/i) && a()
    },
    messageListeners: []
};
/** 初始化浏览器
 *
 */
function initBrowser() {
    Browser.i18n = chrome.i18n;
    Browser.extension = chrome.extension;
    Browser.agent = null;
    Browser.keyCombos = {};
    Browser.currentKeys = {};
    Browser.safariPopoverVisibilityCheckInterval = 0;
    Browser.safariBrowserActionClickHelper = function () {
        console.log("do nothing on browser action click - default handler")
    };
    Browser.safariBrowserActionClickHandler = function (a) {
        Browser.safariBrowserActionClickHelper(a)
    };
    Browser.browserActionOnClickedListeners = [];
    Browser.sendToTab = function (a, b, c) {
        chrome.tabs.sendMessage ? chrome.tabs.sendMessage(a.id, b, c) : chrome.tabs.sendRequest(a.id, b, c)
    };
    /** 发送Message
     *
     * @param attr
     * @param call
     */
    Browser.sendToExtension = function (attr, call) {
        try {
            chrome.runtime &&
            chrome.runtime.sendMessage ? chrome.runtime.sendMessage(attr) : chrome.extension &&
            chrome.extension.sendMessage ? chrome.extension.sendMessage(attr) : chrome.extension.sendRequest(attr)
        } catch (c) {
            if (call) call();
            else throw c;
        }
    };
    /** 获得浏览器类型
     *
     * @returns {null|*}
     */
    Browser.getAgent = function () {
        if (Browser.agent) return Browser.agent;
        var a = "Unknown/1.0",
            b = /^Mozilla\/\d+(\.\d+)*\s+\(.*?([^;()]*(Windows|OS X|Linux)[^;()]*).*?\)/i.exec(navigator.userAgent);
        b && b[2] && (a = b[2].trim());
        a = a.replace(/\s+(\S*\d)/, "/$1");
        b = "0.0";
        SAFARI ? (b = navigator.userAgent.replace(/^.*Version\/([0-9.]+).*$/, "$1"), b == navigator.userAgent && (b = "0.0"), a += "Safari/" + b) : (b = navigator.userAgent.replace(/^.*Chrome\/([0-9.]+).*$/, "$1"), b == navigator.userAgent && (b = "0.0"), a += "Chrome/" + b);
        Browser.agent = a + ";";
        return Browser.agent
    };
    /** 移除消息事件
     *
     */
    Browser.removeMessageHandlers = function () {
        Browser.messageListeners = []
    };
    /**增加消息事件
     *
     * @param a
     * @param b
     */
    Browser.addMessageHandlers = function (a, b) {
        var c;
        c = function (b, c, d) {
            if (!c || c.id !== chrome.i18n.getMessage("@@extension_id") && c.sender && c.sender.id !== chrome.i18n.getMessage("@@extension_id")) console.log("Got request from unexpected sender. Ignoring.");
            else {
                if (b.name && a[b.name]) a[b.name](b, c, d);
                if (d) return !0
            }
        };
        chrome.extension.onMessage ? chrome.extension.onMessage.addListener(c) : chrome.extension.onRequest.addListener(c);
        Browser.messageListeners.push(c)
    };
    /** 添加键盘按下事件
     *
     * @param a
     */
    Browser.addKeyboardHandlers = function (a) {
        for (var b in a) Browser.keyCombos[b] = a[b]
    };
    Browser.handleKeys = function (a) {
        var b = [],
            c;
        for (c in Browser.currentKeys) b.push(parseInt(c));
        b.sort(function (a, b) {
            return a - b
        });
        b = b.join(" + ");
        if (Browser.keyCombos[b]) Browser.keyCombos[b](b, a);
        Browser.currentKeys = {}
    };
    Browser.setIcon = function (a) {
        chrome.browserAction.setIcon({
            path: {
                19: chrome.extension.getURL(a + "-19x19.png"),
                38: chrome.extension.getURL(a + "-19x19@2x.png")
            }
        })
    };
    Browser.setTitle = function (a) {
        chrome.browserAction.setTitle({
            title: a
        })
    };
    Browser.setBrowserActionClickHandler = function (a) {
        chrome.browserAction.onClicked && !chrome.browserAction.onClicked.hasListener(a) && (Browser.browserActionOnClickedListeners.push(a), chrome.browserAction.onClicked.addListener(a))
    };
    Browser.removeBrowserActionClickHandler = function (a) {
        if (chrome.browserAction.onClicked) {
            a || (a = Browser.browserActionOnClickedListeners[0] ? Browser.browserActionOnClickedListeners[0] : null);
            var b = Browser.browserActionOnClickedListeners.indexOf(a); -1 < b && Browser.browserActionOnClickedListeners.splice(b, 1);
            chrome.browserAction.onClicked.removeListener(a)
        }
    };
    Browser.insertJS = function (a, b) {
        chrome.tabs.executeScript(null, {
                file: a
            },
            b)
    };
    Browser.insertCSS = function (a, b) {
        chrome.tabs.insertCSS(null, {
                file: a
            },
            b)
    };
    Browser.captureVisibleTab = function (a, b) {
         chrome.tabs.captureVisibleTab(a.windowId, {
                format: "png"
            },
            b)
    };
    Browser.getCurrentTab = function (a) {
        chrome.tabs.query({
                active: !0,
                currentWindow: !0
            },
            function (b) {
                b && 0 < b.length ? a(b[0]) : (console.log("chrome tabs query did not return a result while getting current tab"), a())
            })
    };
    Browser.getAllTabs = function (a) {
        chrome.tabs.query({},
            a)
    };
    Browser.setPopup = function (a) {
        chrome.browserAction.setPopup({
            popup: a
        })
    };
    Browser.closeTab = function (a) {
        chrome.tabs.remove(a.id)
    };
    window.addEventListener("keydown",
        function (a) {
            189 == a.keyCode && a.altKey ? Browser.currentKeys[76] = a : 188 == a.keyCode && a.altKey ? Browser.currentKeys[80] = a : 190 == a.keyCode && a.altKey ? Browser.currentKeys[88] = a : Browser.currentKeys[a.keyCode] = a
        });
    window.addEventListener("keyup",
        function (a) {
            Browser.handleKeys(a.srcElement)
        });
    Object.preventExtensions(Browser)
}
Browser.runIfInTopFrame(initBrowser);